package org.budo.support.lang.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author li
 * @version 1 (2016年11月16日 下午10:00:49)
 * @since Java7
 */
public class ThreadUtil {
    private static final Logger log = LoggerFactory.getLogger(ThreadUtil.class);

    /**
     * 根据线程名称判断线程是否已经在运行
     */
    public static boolean isActive(String threadName) {
        if (StringUtil.isBlank(threadName)) {
            log.error("#19 isActive, threadName=" + threadName);
            return false;
        }

        int activeCount = Thread.activeCount();
        Thread[] threadArray = new Thread[activeCount];
        Thread.enumerate(threadArray);

        for (int i = 0; i < threadArray.length; i++) {
            if (threadArray[i].getName().equals(threadName)) {
                return true;
            }
        }

        return false;
    }

    public static Thread getThreadByName(String threadName) {
        int activeCount = Thread.activeCount();
        Thread[] threadArray = new Thread[activeCount];
        Thread.enumerate(threadArray);

        for (int i = 0; i < threadArray.length; i++) {
            Thread each = threadArray[i];
            if (null != each && each.getName().equals(threadName)) {
                return each;
            }
        }

        return null;
    }

    /**
     * @param millis 毫秒
     */
    public static void sleep(Number millis) {
        if (null == millis || millis.intValue() < 1) {
            if (log.isDebugEnabled()) {
                log.debug("#19 sleep, millis=" + millis);
            }

            return;
        }

        try {
            Thread.sleep(millis.longValue());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void wait(Class<?> type) {
        try {
            type.wait();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static ThreadGroup getRootThreadGroup() {
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        while (true) {
            ThreadGroup parent = threadGroup.getParent();
            if (null == parent) {
                break;
            }

            threadGroup = parent;
        }
        return threadGroup;
    }
}